import Axios from 'axios';
import {Message} from "element-ui";
// 配置文件
const $config = require("@/config");
// 实例化Axios
let instance = Axios.create({});
// 请求拦截器，添加URL前缀或其他请求头等
instance.interceptors.request.use(config => {
  config.baseURL = $config.BACKEND_API_URL;
  console.log('instance.interceptors.request.use>>>>>>>', config);
  return config;
}, error => {
  return Promise.error(error);
});
// 响应拦截器
instance.interceptors.response.use(response => {
  console.log('instance.interceptors.response.use<<<<<<', response);
  if (response.status === 200 && response.data) {
    if (response.data.code === '0') {
      return Promise.resolve(response.data.data);
    }
    Message({
      showClose: true,
      message: response.data.message || '未知异常',
      type: 'error'
    });
    return Promise.reject(response.data);
  }
  Message({
    showClose: true,
    message: response.data.message || '未知异常',
    type: 'error'
  });
  return Promise.reject(response);
}, err => {
  console.log('调用接口异常：', err);
  if (err && err.response) {
    switch (err.response.status) {
      case -200:
        err.message = '服务器错误';
        break;
      case 400:
        err.message = '请求错误';
        break;
      case 401:
        err.message = '未授权，请登录';
        break;
      case 403:
        err.message = '拒绝访问';
        break;
      case 404:
        err.message = `请求地址错误：${err.response.config.url}`;
        break;
      case 408:
        err.message = '请求超时';
        alert('请求超时，请秒后再试');
        break;
      case 500:
        err.message = '服务器内部错误';
        break;
      case 501:
        err.message = '服务未实现';
        break;
      case 502:
        err.message = '网关错误';
        break;
      case 503:
        err.message = '服务不可用';
        break;
      case 504:
        err.message = '网关超时';
        break;
      case 505:
        err.message = 'HTTP版本不受支持';
        break;
      default:
    }
  }
  Message({
    showClose: true,
    message: err.message || '未知异常',
    type: 'error'
  });
  return Promise.reject(err);
});

/**
 * 封装http请求
 *
 * @param method 请求方法，GET|POST|PUT|DELETE
 * @param url IP端口后面的url地址
 * @param params 传输参数
 * @returns {Promise} 返回Promise
 */
function http(method, url, params) {
  const config = {
    url,
    method
  };
  if (params && method === 'GET' || params && method === 'DELETE') {
    config.params = params;
  } else if (params) {
    config.data = params;
  }
  return instance(config);
}

export const get = (url, params) => http('GET', url, params);
export const post = (url, params) => http('POST', url, params);
export const put = (url, params) => http('PUT', url, params);
export const del = (url, params) => http('DELETE', url, params);
export default {
  get,
  post,
  put,
  del
};
